class User < ActiveRecord::Base
  include BCrypt

  attr_accessible :email, :password

  validates :email, :uniqueness => true,
            :format => /\A[^@]+@[^@]+\z/

  before_create :generate_activation_token

  def password
    nil
  end

  def password=(plain_text)
    self.encrypted_password = Password.create(salt plain_text)
  end

  def password_valid?(plain_text)
    return false unless encrypted_password
    Password.new(encrypted_password) == salt(plain_text)
  end

  def authenticatable_salt
    encrypted_password && encrypted_password[-31..-1]
  end

  def activated?
    !!activated_at
  end

  def as_json(options={})
    options[:except] = [options[:except]].flatten.compact.push(:encrypted_password, :activation_token)
    super(options)
  end

  private
  def salt(plain_text)
    STATIC_SALT + plain_text
  end

  def generate_activation_token
    self.activation_token = SecureRandom.urlsafe_base64(32)
  end
end